<template>
  <div class="container">
    <div class="card-wrap">
      <el-row type="flex" justify="start" :gutter="16">
        <el-col v-for="(item, index) in state.tableData" :key="index" :xs="24" :sm="12" :md="6" :lg="6"
                class="card-col">
          <el-card class="card-item">
            <img :src="item.cover" alt="服务封面" class="image">
            <div class="card-content">
              <div class="title-with-tag">
                <p class="card-title">{{ item.name }}</p>
                <el-tag :type="item.type === '上门服务' ? 'primary' : 'success'">{{ item.type }}</el-tag>
              </div>
              <el-tooltip :content="item.description" placement="top">
                <p class="dialog-description-label">{{ truncateDescription(item.description) }}</p>
              </el-tooltip>
            </div>
            <div class="button-container">
              <el-button type="primary" :icon="Edit" @click="handleReview(item)">服务预约</el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 预约弹窗 -->
    <el-dialog v-model="dialogVisible" title="预约表单" width="30%">
      <div class="review-form">
        <el-form :model="form" label-width="120px">
          <el-form-item label="服务名称">
            <el-input v-model="form.serviceName" disabled/>
          </el-form-item>
          <el-form-item label="服务类型">
            <el-input v-model="form.serviceType" disabled/>
          </el-form-item>
          <el-form-item label="预约人">
            <el-input v-model="form.reservationName" disabled/>
          </el-form-item>
          <el-form-item label="预约日期">
            <el-date-picker
                v-model="form.reservationTime"
                type="datetime"
                placeholder="Select date and time"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="紧急联系人">
            <el-input v-model="form.emergencyContactPhone" placeholder="请输入紧急联系人电话"/>
          </el-form-item>
          <el-form-item label="服务地址">
            <el-input v-model="form.serviceAddress" placeholder="请输入服务地址"/>
          </el-form-item>
        </el-form>
        <div class="button-center">
          <ServiceReservationButton @click="submitReview"/>
        </div>
      </div>
    </el-dialog>
  </div>
  <el-pagination
      background
      layout="prev, pager, next"
      :total="state.total"
      :current-page="state.currentPage"
      :page-size="state.pageSize"
      class="pagination"
      @current-change="handlePageChange"
  />
  <div class="footer">
    <div>社区养老服务整合平台</div>

  </div>
</template>

<script lang="ts" setup>
import {onMounted, reactive, ref} from 'vue'
import {queryElderlyServiceList, serviceReservationApi} from '../../service/elderlyServiceApi.js'
import {Edit} from '@element-plus/icons-vue'
import {ElMessage} from 'element-plus'
import {getLoginerInfo} from "../../service/userApi";
import ServiceReservationButton from "../../components/ServiceReservationButton.vue";

// 数据列表
const state = reactive({
  tableData: [], // 数据列表
  total: 0, // 总条数
  currentPage: 1, // 当前页
  pageSize: 8, // 分页大小
})

// 预约弹窗
const dialogVisible = ref(false)
const currentReviewRow = ref(null)
const form = reactive({
  serviceName: '',   // 服务名称
  serviceType: '',   // 服务类型
  reservationId: '', // 预约者id从登录信息获取
  reservationName: '', // 预约者姓名从登录信息获取
  reservationTime: '', // 预约日期
  emergencyContactPhone: '',  // 紧急联系人电话
  serviceAddress: ''   // 服务地址
})

// 初始渲染
onMounted(() => {
  getIndexConfig()
  getUserInfo()
})

// 打开预约弹窗
const handleReview = (row) => {
  currentReviewRow.value = row
  form.serviceName = row.name
  form.serviceType = row.type // 服务类型从数据中获取
  form.reservationTime = ''
  form.emergencyContactPhone = ''
  form.serviceAddress = ''
  dialogVisible.value = true
}

// 提交预约
const submitReview = async () => {
  if (!form.reservationTime || !form.emergencyContactPhone || !form.serviceAddress) {
    ElMessage.error('请填写所有必填项')
    return
  }

  try {
    const params = {
      // todo 服务预约接口需要的参数(包括表单提交的以及服务信息的)
      serviceId: currentReviewRow.value.id,
      userId: form.reservationId,
      userName: form.reservationName,
      reservationTime: form.reservationTime,
      emergencyContactPhone: form.emergencyContactPhone,
      serviceAddress: form.serviceAddress
    }
    const result = await serviceReservationApi(params)
    if (result.code === 200) {
      dialogVisible.value = false
      ElMessage.success('预约成功')
      await getIndexConfig()
    } else {
      ElMessage.error('预约失败')
    }
  } catch (error) {
    console.error('提交预约时出错', error)
    ElMessage.error('提交预约时出错')
  }
}

// 分页处理
const handlePageChange = (val) => {
  state.currentPage = val
  getIndex()
}

// 获取列表数据
const getIndex = async () => {
  try {
    const params = {
      pageNum: state.currentPage,
      pageSize: state.pageSize,
    }
    const response = await queryElderlyServiceList(params)
    state.total = response.data.total || 0
  } catch (error) {
    console.error('获取数据失败:', error)
  }
}

// 初始化用户信息
const getUserInfo = async () => {
  const response = await getLoginerInfo()
  form.reservationName = response.data.name
  form.reservationId = response.data.id
}

// 截取描述内容
const truncateDescription = (description) => {
  if (description.length > 30) {
    return description.substring(0, 30) + '...'
  }
  return description
}

const getIndexConfig = async () => {
  const params = {
    pageNum: state.currentPage,
    pageSize: state.pageSize,
  }
  const response = await queryElderlyServiceList(params)
  state.tableData = response.data.records.map(item => ({
    ...item,
    type: item.id % 2 === 0 ? '上门服务' : '机构服务' // 临时写死服务类型
  }))
  state.total = response.data.total || 0
}
</script>

<style scoped>
.title-with-tag {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-content {
  padding: 16px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 90px;
}

.container {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 16px;
}

.card-wrap {
  width: 100%;
}

.card-col {
  margin-bottom: 16px;
}

.card-item {
  width: 100%;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: box-shadow 0.3s ease;
}

.card-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.review-form {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 100%;
}

.button-center {
  display: flex;
  justify-content: center;
  margin-top: 20px; /* 可根据需要调整 */
}

.image {
  width: 100%;
  height: 180px;
  object-fit: cover;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 3px;
  color: #333;
}

.button-container {
  padding: 7px;
  text-align: center;
}

.pagination {
  display: flex;
  margin-top: -10px;
  margin-left: 360px;
}

.dialog-description-label {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 8px;
}

.footer {
  font-size: 14px;
  height: 100px;
  border-top: 1px solid #e9e9e9;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  gap: 10px;
}

.beian-footer a {
  color: #1D1D26;
  font-size: 14px;
  text-decoration-line: underline;
}

.beian-footer a:hover {
  color: #409EFF;
}
</style>